package com.hue.controller;


import com.hue.entity.EduChapter;
import com.hue.entity.R;
import com.hue.entity.vo.ChapterVo;
import com.hue.service.EduChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author 姚凤桥
 * @since 2021-06-13
 */
@RestController
@CrossOrigin
@RequestMapping("/chapter")
public class EduChapterController {
    @Autowired
    private EduChapterService eduChapterService;

    //根据courseId查询所有chapter
    @GetMapping("/findByCourseId/{courseId}")
    public R findByCourseId(@PathVariable("courseId") String courseId) {
        try {
            List<ChapterVo> chapterVos = eduChapterService.findByCourseId(courseId);
            return R.ok().data("chapters", chapterVos);
        } catch (Exception e) {
            return R.ok().data("msg", e.getMessage());
        }
    }

    @PostMapping("/add")
    public R add(@RequestBody EduChapter eduChapter) {
        eduChapterService.save(eduChapter);
        return R.ok();
    }

    //根据id查询chapter
    @GetMapping("/findById/{id}")
    public R findById(@PathVariable("id") String id) {
        EduChapter eduChapter = eduChapterService.getById(id);
        return R.ok().data("chapter", eduChapter);
    }

    //修改chapter
    @PostMapping("/update")
    public R update(@RequestBody EduChapter eduChapter) {
        eduChapterService.updateById(eduChapter);
        return R.ok();
    }

    //根据id删除chapter,如果章节下面还有小节，就删除失败
    @GetMapping("/deleteById/{id}")
    public R deleteById(@PathVariable("id") String id) {
        boolean b = eduChapterService.deleteById(id);
        return b ? R.ok() : R.error();
    }
}

